package com.example.springbootfile.controller;

import com.example.springbootfile.config.FileConfig;
import com.example.springbootfile.utils.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class FileController {

    @GetMapping("/index")
    public String index() {
        return "index";
    }

    /**
     *  单文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    @ResponseBody
    public String fileUpload(@RequestParam("fileName") MultipartFile file) {
        //判断文件是否为空
        if (file.isEmpty()) {
            return "空文件";
        }
        if (file.getSize() > FileConfig.FILE_MAX_SIZE) {
            return "文件超过指定大小";
        }
        //获取文件名
        String fileName = file.getOriginalFilename();
        //获取文件后缀
        String type =fileName.indexOf(".") != -1 ? fileName.split("[.]")[1] : null;
        //文件格式判断
        if (!Arrays.asList(FileConfig.UPLOAD_IMAGE_TYPES).contains(type.toLowerCase())
                && !Arrays.asList(FileConfig.UPLOAD_FILE_TYPES).contains(type.toLowerCase())) {
            return "图片类型不对";
        }
        //加入当前时间重命名文件，尽量避免文件名称重复
        String path = FileConfig.UPLOAD_PATH + new SimpleDateFormat("yyyyMMddHHmmss").
                format(new Date()) + "_" + fileName;
        File file1 = new File(path);
        //判断文件是否已经存在
        if (file1.exists()) {
            return "文件已存在";
        }
        //判断文件父目录是否存在
        if (!file1.getParentFile().exists()) {
            file1.getParentFile().mkdir();
        }
        try {
            //保存文件
            file.transferTo(file1);
        } catch (IOException e) {
            return "上传文件失败";
        }
        return path;
    }


    /**
     * 多文件上传
     * @param request
     * @return
     */
    @PostMapping("/uploads")
    @ResponseBody
    public Map<String, String> fileUploads(HttpServletRequest request){
        Map<String,String> map=new HashMap<String,String>();
        //fileNames为页面的文件控件的name
        List<MultipartFile> files =((MultipartHttpServletRequest)request).getFiles("fileNames");
        for (MultipartFile file:files) {
            //获取文件名
            String fileName = file.getOriginalFilename();
            if (!file.isEmpty()) {
                if (file.getSize() > FileConfig.FILE_MAX_SIZE) {
                    map.put(fileName,"文件超过指定大小");
                    continue;
                }
                //获取文件后缀
                String type =fileName.indexOf(".") != -1 ? fileName.split("[.]")[1] : null;
                //文件格式判断
                if (!Arrays.asList(FileConfig.UPLOAD_IMAGE_TYPES).contains(type.toLowerCase())
                        && !Arrays.asList(FileConfig.UPLOAD_FILE_TYPES).contains(type.toLowerCase())) {
                    map.put(fileName,"图片类型不对");
                    continue;
                }
                //加入当前时间重命名文件，尽量避免文件名称重复
                String path = FileConfig.UPLOAD_PATH + new SimpleDateFormat("yyyyMMddHHmmss").
                        format(new Date()) + "_" + fileName;
                File file1 = new File(path);
                //判断文件是否已经存在
                if (file1.exists()) {
                    map.put(fileName,"文件已存在");
                    continue;
                }
                //判断文件父目录是否存在
                if (!file1.getParentFile().exists()) {
                    file1.getParentFile().mkdir();
                }
                try {
                    //保存文件
                    file.transferTo(file1);
                } catch (IOException e) {
                    map.put(fileName,"上传文件失败");
                }
            } else {
                map.put(fileName,"空文件");
            }
        }

       return map;

    }


    /**
     * 文件下载
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/download")
    @ResponseBody
    public String downloadFile(HttpServletRequest request, HttpServletResponse response) {
        // 生成的文件名
        String fileName = "a.jpg";
        if (fileName != null) {
            //设置文件路径
            File file = new File(FileConfig.UPLOAD_PATH+fileName);
            //File file = new File(realPath , fileName);
            if (file.exists()) {
                // 设置强制下载不打开
                response.setContentType("application/force-download");
                // 设置文件名
                response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    return "下载成功";
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return "下载失败";
    }
}
